package com.zensun.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.zensun.common.annotation.Log;
import com.zensun.common.constant.UserConstants;
import com.zensun.common.core.controller.BaseController;
import com.zensun.common.core.domain.BaseEntity;
import com.zensun.common.core.domain.R;
import com.zensun.common.core.page.PageDataInfo;
import com.zensun.common.enums.BusinessType;
import com.zensun.common.utils.spring.ServletUtils;
import com.zensun.framework.web.service.SysPermissionService;
import com.zensun.framework.web.service.TokenService;
import com.zensun.system.domain.SysRole;
import com.zensun.system.domain.dto.SysRoleDto;
import com.zensun.system.domain.model.LoginUser;
import com.zensun.system.domain.vo.*;
import com.zensun.system.service.ISysRoleService;
import com.zensun.system.service.impl.SysUserServiceImpl;
import com.zensun.system.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息
 *
 * @author gmk
 */
@Api(value = "角色管理", tags = "角色模块")
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserServiceImpl userService;

    @ApiOperation("查询角色列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public R<PageDataInfo<SysRoleVo>> list(SysRoleDto roleDto) {
        startPage();
        List<SysRoleVo> list = roleService.selectRoleList(roleDto);

        PageDataInfo pageDataTable = getPageDataTable(list);

        List<SysRoleVo> stream = pageDataTable.getList();
        List<SysRoleVo> result = stream.stream().map(sysRoleVo -> {
            sysRoleVo.setIsSelf(SecurityUtils.isAdmin(sysRoleVo.getRoleId()));
            return sysRoleVo;
        }).collect(Collectors.toList());
        pageDataTable.setList(result);
        return R.success(getPageDataTable(list));
    }

    /**
     * 根据角色编号获取详细信息
     */
    @ApiOperation("根据角色ID获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R<SysRoleDetailVo> getInfo(@PathVariable Long roleId) {
        return R.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @ApiOperation("新增角色")
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated(BaseEntity.AddGrop.class) @RequestBody SysRole role) {
        return R.toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @ApiOperation("修改角色")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated(BaseEntity.UpdateGrop.class) @RequestBody SysRole role) {
        // tokenService,permissionService在逻辑层注入不了，故放到了控制层
        return R.toAjax(roleService.updateRole(role));

    }

    /*
     * 更新缓存用户权限
     */
    private void reflash() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (ObjectUtil.isNotNull(loginUser.getUser()) && !UserConstants.ADMIN_ID.equals(loginUser.getUser().getUserId())) {
            loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
            //loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
            // loginUser.setUser(userService.selectUserByTelePhone(telephone));
            tokenService.setLoginUser(loginUser);
        }
    }

    /**
     * 根据角色ID获取详细数据权限信息································接口暂时不用
     */
    @ApiOperation("根据角色ID获取详细数据权限信息")
    @PreAuthorize("@ss.hasPermi('system:role:datascope')")
    @GetMapping(value = "/dataScope/{roleId}")
    public R<SysRoleDataScopeVo> selectRoleDataScopeById(@PathVariable Long roleId) {
        return R.success(roleService.selectRoleDataScopeById(roleId));
    }

    /**
     * 角色绑定数据权限 ································接口暂时不用
     */
    @ApiOperation("角色绑定数据权限")
    @PreAuthorize("@ss.hasPermi('system:role:datascope')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PatchMapping("/banding4dataScope")
    public R dataScope(@RequestBody SysRoleDataScopeVo role) {
        return R.toAjax(roleService.authDataScope(role));
    }

    /**
     * 角色绑定菜单权限
     */
    @ApiOperation("角色绑定菜单权限")
    @PreAuthorize("@ss.hasPermi('system:role:menu')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PatchMapping("/banding4menu")
    public R roleBanding4menu(@RequestBody SysRoleMenuIdVo sysRoleMenuIdVo) {
        if (roleService.roleBanding4menu(sysRoleMenuIdVo) > 0) {
            // 更新缓存用户权限
            // reflash();
            return R.success();
        }
        return R.error("修改菜单权限失败");
    }

    /**
     * 删除角色
     */
    @ApiOperation("删除角色")
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public R remove(@ApiParam("ID集合（1,2）") @PathVariable Long[] roleIds) {
        return R.toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @ApiOperation("获取角色选择框列表")
    @GetMapping("/optionselect")
    public R<List<SysRoleSelectVo>> optionselect() {
        return R.success(roleService.optionselect(new SysRoleDto()));
    }
}
